﻿using System.Collections.Generic;
using AspNetInfo.Helpers;
using AspNetInfo.Core;
using System.Web;
using CommonGenius.Collections;
using System;
using System.Data;

namespace AspNetInfo.Detectors
{
    public class MemoryDetector : IDetector
    {
        public DataTable Detect(EnvironmentPermissions permissions)
        {
            var dt = DetectorHelper.MakeResultTable();

            if (permissions.TrustLevel > AspNetHostingPermissionLevel.Medium)
            {
                var memory = SystemInfo.Memory;
                dt.Rows.Add("Physical Memory Size", FormatNumber(memory.dwTotalPhys));
                dt.Rows.Add("Physical Free Memory Size", FormatNumber(memory.dwAvailPhys));
                dt.Rows.Add("PageFile Size", FormatNumber(memory.dwTotalPageFile));
                dt.Rows.Add("Available PageFile Size", FormatNumber(memory.dwAvailPageFile));
                dt.Rows.Add("Virtual Memory Size", FormatNumber(memory.dwTotalVirtual));
                dt.Rows.Add("Available Memory Size", FormatNumber(memory.dwAvailVirtual));
                dt.Rows.Add("Memory Load", string.Format("{0} %", memory.dwMemoryLoad.ToString("N")));
            }
            return dt;
        }

        public string Name
        {
            get { return "Memory"; }
        }

        // TODO: Move this to a formatter.

        private string FormatNumber(ulong value)
        {
            if (value < 4 * 1024)
            {
                return string.Format("{0} Bytes", value);
            }
            else if (value < (long)4 * 1024 * 1024)
            {
                return string.Format("{0} KB", (value / (double)((long)1024)).ToString("N"));
            }
            else if (value < (long)4 * 1024 * 1024 * 1024)
            {
                return string.Format("{0} MB", (value / (double)((long)1024 * 1024)).ToString("N"));
            }
            else if (value < (long)4 * 1024 * 1024 * 1024 * 1024)
            {
                return string.Format("{0} GB", (value / (double)((long)1024 * 1024 * 1024)).ToString("N"));
            }
            else
            {
                return string.Format("{0} TB", (value / (double)((long)1024 * 1024 * 1024 * 1024)).ToString("N"));
            }
        }

        public string Description
        {
            get { return String.Empty; }
        }

        public string TabName
        {
            get { return Tabs.General; }
        }
    }
}
